//
//  IG_RoundDetailViewController.m
//  iGameApp
//
//  Created by Yf66 on 16/1/12.
//  Copyright © 2016年 WYC. All rights reserved.
//

#import "IG_RoundDetailViewController.h"
#import "IG_iGameTextfieldInPutView.h"

@interface IG_RoundDetailViewController ()<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, UITextViewDelegate>

@property (nonatomic, strong)IG_iGameTextfieldInPutView *tfView;
@end

@implementation IG_RoundDetailViewController

- (void)viewWillAppear:(BOOL)animated {
    IGRightTabBarController *tabBarController = (IGRightTabBarController *)self.navigationController.parentViewController;
    tabBarController.tabBar.hidden = YES;
    
    IGCustomNavigationController *navC = (IGCustomNavigationController *)self.navigationController;
    navC.iconButton.hidden = YES;
    navC.backButton.hidden = NO;
    navC.label.hidden = YES;
    navC.groupButton.hidden = YES;
    navC.image.hidden = YES;
    navC.downImage.hidden = YES;
    [_tableView reloadData];
}



- (void)viewDidLayoutSubviews {
    _tableView.frame = CGRectMake(0,264, kScreenWidth, kScreenHeight - 304);
    _tableView.tableFooterView = [[UIView alloc] init];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView.autoresizesSubviews = NO;
    // Do any additional setup after loading the view from its nib.
    _headerView = [[[UINib nibWithNibName:@"IG_iGameRoundHeaderView" bundle:nil]instantiateWithOwner:self options:nil]firstObject];
    _tableViewCount = -1;
    _isComment = 1;
    CGRect frame = _headerView.frame;
    frame.size.height = 120;
    _headerView.frame = frame;
    [_tableView setTableHeaderView:_headerView];
    [_tableView registerNib:[UINib nibWithNibName:@"IG_iGameRoundTableViewCell" bundle:nil] forCellReuseIdentifier:@"IG_iGameRoundTableViewCell"];
    [_tableView registerNib:[UINib nibWithNibName:@"IG_RoundCommentTableViewCell" bundle:nil] forCellReuseIdentifier:@"IG_RoundCommentTableViewCell"];
    [self setUpAllData];
    [self setUpTableViewData];
    [self setUpCommentData];
    _commentDataArray = [NSMutableArray array];
    [_commentIconBtn addTarget:self action:@selector(commentIconBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [_commentCountLabel addTarget:self action:@selector(commentIconBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
    _tableView.rowHeight = UITableViewAutomaticDimension;
    _tableView.rowHeight = 100;
    [self setTextField];
}

//  评论按钮点击方法
- (void)commentIconBtnClick:(UIButton *)sender {
    if (_count == 0) {

    } else {
        if (_tableView.contentOffset.y < (_tableViewDataArray.count - 1) * 60) {
            [_tableView setContentOffset:CGPointMake(0, (_tableViewDataArray.count - 1) * 60 + 100) animated:YES];
        } else {
            [_tableView setContentOffset:CGPointMake(0, 0) animated:YES];
        }
    }
}

#pragma mark -- 数据请求
- (void)setUpAllData {
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"vid"] = [NSNumber numberWithInteger:[_vid integerValue]];
    _allModel = [[IG_iGameRoundAllModel alloc] init];
    [IGAFNetworking requestWithUrlString:@"http://www.imbatv.cn/api_2_4_0/VideoDetail?" parDic:parDic metho:GET finish:^(NSDictionary *dataDic) {
        NSDictionary *dic = dataDic[@"data"];
        [_allModel setValuesForKeysWithDictionary:dic];
        _headerView.titleLabel.text = _allModel.title;
        [_headerView.titleLabel sizeToFit];
        _headerView.descLabel.text = _allModel.desc;
        [_headerView.descLabel sizeToFit];
        CGRect frame = _headerView.frame;
        frame.size.height = _headerView.titleLabel.frame.size.height + _headerView.descLabel.frame.size.height + 50;
                  if (frame.size.height != 50) {
                      _headerView.frame = frame;
                      [_tableView setTableHeaderView:_headerView];
        }
        NSURL *url = [NSURL URLWithString:_allModel.player_url];
        UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, 200)];
        webView.scalesPageToFit = YES;
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [webView loadRequest:request];
        [self.view addSubview:webView];
        [_tableView reloadData];
    } error:^(NSError *requestError) {
        NSLog(@"请求失败");
    }];
}

//  tableview数据请求
- (void)setUpTableViewData {
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"video_id"] = _vid;
    [IGAFNetworking requestWithUrlString:@"http://www.imbatv.cn/api_2_4_0/get_related_videos_list?match_id=-1" parDic:parDic metho:GET finish:^(NSDictionary *dataDic) {
        NSArray *array = dataDic[@"data"];
        NSString *code = dataDic[@"code"];
        if ([code isEqualToString:@"400"]) {
            _tableViewCount = 0;
            [_tableView reloadData];
        } else {
        _tableViewDataArray = [NSMutableArray array];
        
        if (_tableViewCount != 0) {
            _tableViewCount = array.count;
            for (NSDictionary *dic in array) {
                IG_iGameDetailTableModel *model = [[IG_iGameDetailTableModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [_tableViewDataArray addObject:model];
            }
            [_tableView reloadData];
        }
        }
    } error:^(NSError *requestError) {
        NSLog(@"请求失败");
    }];
}

//  评论数据请求
- (void)setUpCommentData {
  
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"start"] = [NSString stringWithFormat:@"%ld",(long)_requestStart];
    parDic[@"video_id"] = _vid;
    NSDictionary *dic = [IG_UserMessage shareUserMessage].dic;
    NSInteger uid = 0;
    if (dic == nil) {
        uid = -1;
    } else {
        uid = [dic[@"uid"] integerValue];
    }
    uid = -1;
    parDic[@"uid"] = [NSString stringWithFormat:@"%ld",uid];
    [IGAFNetworking requestWithUrlString:@"http://www.imbatv.cn/api_2_4_0/getVideoComment?num=10" parDic:parDic metho:GET finish:^(NSDictionary *dataDic) {
        NSDictionary *dic = dataDic[@"data"];
        NSArray *array = dic[@"comment"];
        _count = [dic[@"counts"] integerValue];
            if (_count == 0) {
                [_commentCountLabel setTitle:@"沙发" forState:(UIControlStateNormal)];
                [_commentIconBtn setImage:[UIImage imageNamed:@"iconfont-iconfontshafa"] forState:(UIControlStateNormal)];
                [_commentDataArray removeAllObjects];
                [_tableView reloadData];
            } else{
                [_commentIconBtn setImage:[UIImage imageNamed:@"iconfont-duihuaqipao3"] forState:(UIControlStateNormal)];
                [_commentCountLabel setTitle:[NSString stringWithFormat:@"%ld",(long)_count] forState:(UIControlStateNormal)];
            }
        if (array.count != 0) {
            _commentDataArray = [NSMutableArray array];
            for (NSDictionary *modelDic in array) {
                IG_iGameRoundCommentModel *model = [[IG_iGameRoundCommentModel alloc] init];
                [model setValuesForKeysWithDictionary:modelDic];
                [_commentDataArray addObject:model];
            }
                            [_tableView reloadData];
        }
        
    } error:^(NSError *requestError) {
        NSLog(@"请求失败");
    }];
}

#pragma mark -- tableview的协议方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (_count == 0 || _tableViewCount == 0) {
        return 1;
    } else if(_count == 0 && _tableViewCount == 0) {
        return 0;
    } else {
        return 2;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0 && _tableViewCount != 0) {
        return _tableViewDataArray.count;
    } else {
        return _commentDataArray.count;
    }
    
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSString *str = @"相关视频";
    if (section == 0 && _tableViewCount != 0 && _tableViewCount != -1) {
        return str;
    }
    else if(_count == 0 && _tableViewCount == 0) {
        return nil;
    } else {
        NSString *string = [NSString stringWithFormat:@"评论 : %ld",(long)_count];
        return string;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dic = [IG_UserMessage shareUserMessage].dic;
    if (indexPath.section == 0 && _tableViewCount != 0) {
        IG_iGameRoundTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"IG_iGameRoundTableViewCell" forIndexPath:indexPath];
        cell.model = _tableViewDataArray[indexPath.row];
        return cell;
    } else {
        IG_RoundCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"IG_RoundCommentTableViewCell" forIndexPath:indexPath];
        IG_iGameRoundCommentModel *model = _commentDataArray[indexPath.row];
        if ([model.uid integerValue] == [dic[@"uid"] integerValue]) {
            cell.deleteBtn.hidden = NO;
        } else {
            cell.deleteBtn.hidden = YES;
        }
        cell.deleteBtn.tag = [model.myID integerValue];
        [cell.deleteBtn addTarget:self action:@selector(deleteBtn:) forControlEvents:(UIControlEventTouchUpInside)];
        cell.model = model;
       cell.topButton.tag = [model.uid integerValue];
//        [cell.topButton addTarget:self action:@selector(topButton:) forControlEvents:(UIControlEventTouchUpInside)];
        return cell;
    }
   
}


- (void)deleteBtn:(UIButton *)sender {
    NSString *newUrl = [NSString stringWithFormat:@"http://www.imbatv.cn/api_2_4_0/delVideoComment?id=%ld",sender.tag];
    [IGAFNetworking requestWithUrlString:newUrl parDic:nil metho:GET finish:^(NSDictionary *dataDic) {
        [self setUpCommentData];
    } error:^(NSError *requestError) {
        
    }];
}




- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && _tableViewCount != 0) {
        return 60;
    } else {
        return 100;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && _tableViewCount != 0) {
        IG_RoundDetailViewController *rdVC = [[IG_RoundDetailViewController alloc] init];
        IG_iGameDetailTableModel *model = _tableViewDataArray[indexPath.row];
        rdVC.vid = model.vidStr;
        [rdVC setUpCommentData];
        [rdVC setUpAllData];
        [rdVC setUpTableViewData];
        [self.navigationController pushViewController:rdVC animated:YES];
        if (_tableViewCount == 1) {
            rdVC.tableViewCount = 0;
        }
    }
}

#pragma mark -- 评论设置
//  textfield设置

- (void)setTextField {
     _tfView = [[UINib nibWithNibName:@"IG_iGameTextfieldInPutView" bundle:nil] instantiateWithOwner:self options:nil].firstObject;
    _tfView.height = 150;
    _commentTF.inputAccessoryView = _tfView;
    _commentTF.delegate = self;
    _tfView.commentTV.delegate = self;
    [_tfView.cancelButton addTarget:self action:@selector(cancelButton:) forControlEvents:(UIControlEventTouchUpInside)];
    [_tfView.sendBtn addTarget:self action:@selector(sendBtn:) forControlEvents:(UIControlEventTouchUpInside)];
}

- (void)cancelButton:(UIButton *)send {
    [_tfView.commentTV resignFirstResponder];
    [_commentTF resignFirstResponder];
  
}

- (void)sendBtn:(UIButton *)sender {
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    NSDictionary *dic = [IG_UserMessage shareUserMessage].dic;
    NSString *city = @"上海";
    parDic[@"city"] = [city stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    parDic[@"content"] = [_tfView.commentTV.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    parDic[@"uid"] = [NSString stringWithFormat:@"%@",dic[@"uid"]];
    parDic[@"video_id"] = _vid;
    [IGAFNetworking newRequestWithUrlString:@"http://www.imbatv.cn/api_2_4_0/addVideoComment" parDic:parDic method:POST finish:^(NSDictionary *dataDic) {
        [_commentTF resignFirstResponder];
        [_tfView.commentTV resignFirstResponder];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"评论成功" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
        [alertView show];
        _tfView.commentTV.text = nil;
        _commentTF.text = nil;
        _isComment = 0;
        [self setUpCommentData];
    } error:^(NSError *requestError) {
        NSLog(@"请求失败");
    }];
    
    
}



#pragma mark -- Textfield协议方法



- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if ([IG_UserMessage shareUserMessage].isLoading == NO) {
        [_commentTF resignFirstResponder];
        IGLoginViewController *loginVC = [[IGLoginViewController alloc] init];
        [self presentViewController:loginVC animated:YES completion:nil];
    } else {
        if (_isComment == 1) {
             [self performSelector:@selector(resignTFFirstResponder) withObject:nil afterDelay:1];
        } else {
            [_commentTF resignFirstResponder];
            [_tfView.commentTV resignFirstResponder];
            _isComment = 1;
        }
   
    }
}
- (void)resignTFFirstResponder {
    [_commentTF resignFirstResponder];
    [_tfView.commentTV becomeFirstResponder];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
